package com.huilian.iotbox.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huilian.iotbox.admin.dao.MemberDao;
import com.huilian.iotbox.admin.dao.StatsStoreDao;
import com.huilian.iotbox.admin.service.*;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.dto.*;
import com.huilian.iotbox.data.enums.*;
import com.huilian.iotbox.data.po.MerchantStore;
import com.huilian.iotbox.data.po.StatsStore;
import com.huilian.iotbox.data.po.StatsStoreDetail;
import com.huilian.iotbox.data.po.StatsUser;
import com.huilian.iotbox.data.properties.ConfigProperties;
import com.huilian.iotbox.data.properties.FileProperties;
import com.huilian.iotbox.data.service.LawHolidayService;
import com.huilian.iotbox.data.service.StatsStoreDetailCommonService;
import com.huilian.iotbox.data.utils.DateTimeUtils;
import com.huilian.iotbox.data.utils.SciCalUtils;
import com.huilian.iotbox.data.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Font;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lizhiquan
 * @CreateDate: 2021-04-12 10:59
 * @Description:
 */
@Slf4j
@Service
public class StatsStoreServiceImpl implements StatsStoreService {
    private static Integer TYPE_DAY = 1;
    private static Integer TYPE_MONTH = 2;
    @Autowired
    private OrderService orderService;
    @Resource
    private StatsStoreDao statsStoreDao;
    @Autowired
    private FileProperties fileProperties;
    @Autowired
    private StatsStoreDetailService statsStoreDetailService;
    @Autowired
    private MemberStoreBalanceService memberStoreBalanceService;
    @Autowired
    private StatsStoreDetailCommonService statsStoreDetailCommonService;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private ConfigProperties configProperties;

    @Override
    public PageInfo findList(StatsStoreDto statsStoreDto) {
        if (statsStoreDto.getType().equals(1)) {
            statsStoreDto.setStartDateStr(DateTimeUtils.formatByPattern(statsStoreDto.getCreateTime(), "yyyy-MM-dd"));
            statsStoreDto.setEndDateStr(DateTimeUtils.formatByPattern(statsStoreDto.getUpdateTime(), "yyyy-MM-dd"));
        } else {
            statsStoreDto.setStartDateStr(DateTimeUtils.formatByPattern(statsStoreDto.getCreateTime(), "yyyy-MM"));
            statsStoreDto.setEndDateStr(DateTimeUtils.formatByPattern(statsStoreDto.getUpdateTime(), "yyyy-MM"));
        }
        PageHelper.startPage(statsStoreDto.getPageNum(), statsStoreDto.getPageSize(), "ss.dateStr desc, ss.turnover desc");
        List<StatsStoreVo> statsStoreVoList = statsStoreDao.findList(statsStoreDto);
        statsStoreVoList.forEach(data -> {
            data.setActivityTurnover(data.getSeckillMoney().add(data.getGroupBookingMoney()).add(data.getConsumptionOfRedEnvelopesMoney()).add(data.getMemberOfTheStoredValueMoney()));
        });
        PageInfo pagResult = new PageInfo(statsStoreVoList);
        return pagResult;
    }

    @Override
    public void statsMonthStoreJob(String startDateStr, String endDateStr) {
        // 月统计场地记录详情
        List<StatsStoreDetail> statsStoreDetailList = statsStoreDetailService.statsMonthStoreDetail(startDateStr, endDateStr);
        String data = DateTimeUtils.getPreviousMonth();
        for (StatsStoreDetail statsStoreDetail : statsStoreDetailList) {
            statsStoreDetail.setDateStr(data);
            statsStoreDetail.setType(TYPE_MONTH);
            statsStoreDetailService.insert(statsStoreDetail);
        }

        // 月统计场地记录
        List<StatsStore> statsStoreList = statsStoreDao.findStatsStoreList(startDateStr, endDateStr);
        for (StatsStore statsStore : statsStoreList) {
            statsStore.setDateStr(data);
            statsStore.setType(TYPE_MONTH);
            statsStoreDao.insert(statsStore);
            StatsStoreDetail statsStoreDetail = new StatsStoreDetail();
            statsStoreDetail.setStatsStoreId(statsStore.getId());
            statsStoreDetail.setDateStr(statsStore.getDateStr());
            statsStoreDetail.setMchStoreId(statsStore.getMchStoreId());
            statsStoreDetailService.updateByDateAndMchStoreId(statsStoreDetail);
        }
    }

    @Override
    public List<StatsUser> statsDayUser(String yesterday, Integer statsType) {
        return statsStoreDao.statsDayUser(yesterday, statsType);
    }


    @Override
    public void statsStoreByMerchantStoreIdAndMemberIdJobV2(String startTime, String endTime, Integer statsType, String yesterday) {
        /**
         * stats_store_detail
         *      statsType=1
         *          select
         *              mchStoreId
         *              memberId
         *          group by
         *              memberId
         *              merchantStoreId
         *
         *      statsType=2
         *          select
         *              mchStoreId
         *              deviceNo
         *              memberId
         *          group by
         *              deviceNo
         *              memberId
         *              merchantStoreId
         *
         * stats_store
         *      statsType=1
         *          select
         *              mchStoreId
         *          group by
         *              mchStoreId
         *      statsType=2
         *          select
         *              mchStoreId
         *              agencyId
         *          group by
         *              agencyId
         *              mchStoreId
         *
         */
        Map<String, StatsStoreDetail> statsStoreDetailMap = new HashMap<>();

        /**购买订单*/
        List<StatsStoreDetail> statsOrderList = statsStoreDetailService.statsStatsStoreDetailByOrderV2(startTime, endTime, statsType);
        for (StatsStoreDetail item : statsOrderList) {
            String key = this.generateKey(item, statsType);

            StatsStoreDetail statsStoreDetail = statsStoreDetailMap.get(key);
            if (StringUtils.isEmpty(statsStoreDetail)) {
                statsStoreDetail = new StatsStoreDetail();
                this.initData(statsStoreDetail, item, statsType, yesterday);
            }
            statsStoreDetail.setTurnover(item.getTurnover());
            statsStoreDetail.setTurnoverOnLine(item.getTurnoverOnLine());
            statsStoreDetail.setTurnoverOffline(item.getTurnoverOffline());
            statsStoreDetail.setTurnoverDouYin(item.getTurnoverDouYin());
            statsStoreDetail.setTurnoverMeiTuan(item.getTurnoverMeiTuan());
            statsStoreDetail.setOrderCount(item.getOrderCount());
            statsStoreDetail.setOrderCountOnLine(item.getOrderCountOnLine());
            statsStoreDetail.setOrderCountOffline(item.getOrderCountOffline());
            statsStoreDetail.setHandlingCharge(item.getHandlingCharge());
            statsStoreDetail.setSettlementMoney(item.getSettlementMoney());
            statsStoreDetail.setPlatformSettlementMoney(item.getPlatformSettlementMoney());
            statsStoreDetail.setWxMoney(item.getWxMoney());
            statsStoreDetail.setAliMoney(item.getAliMoney());
            statsStoreDetail.setCashMoney(item.getCashMoney());
            statsStoreDetail.setOutCoinSales(item.getOutCoinSales());
            statsStoreDetail.setOutCoinGive(item.getOutCoinGive());
            statsStoreDetail.setSelfServiceTerminalCash(item.getSelfServiceTerminalCash());
            statsStoreDetail.setManualTerminalCash(item.getManualTerminalCash());
            statsStoreDetail.setTurnoverOfflineCollectionCode(item.getTurnoverOfflineCollectionCode());
            statsStoreDetail.setScanningFee(item.getScanningFee());
            statsStoreDetail.setTiktokCancellationFee(item.getTiktokCancellationFee());
            statsStoreDetail.setMeiTuanCancellationFee(item.getMeiTuanCancellationFee());
            statsStoreDetailMap.put(key, statsStoreDetail);
        }

        /**游戏币营业额，通用商品营业额，套票商品营业额 */
        List<StatsStoreDetail> statsOrderItemList = statsStoreDetailService.statsStatsStoreDetailByOrderItem(startTime, endTime, statsType);
        for (StatsStoreDetail item : statsOrderItemList) {
            String key = this.generateKey(item, statsType);

            StatsStoreDetail statsStoreDetail = statsStoreDetailMap.get(key);
            if (StringUtils.isEmpty(statsStoreDetail)) {
                statsStoreDetail = new StatsStoreDetail();
                this.initData(statsStoreDetail, item, statsType, yesterday);
            }
            statsStoreDetail.setTurnoverGameCoin(item.getTurnoverGameCoin());
            statsStoreDetail.setTurnoverGeneralCommodity(item.getTurnoverGeneralCommodity());
            statsStoreDetail.setTurnoverTicketPackageCommodity(item.getTurnoverTicketPackageCommodity());
            statsStoreDetailMap.put(key, statsStoreDetail);
        }

        /** 抖音美团核销手续费 */
        List<StatsStoreDetail> statsLedgerOrderList = statsStoreDetailService.statsStatsStoreDetailByLedgerOrder(startTime, endTime, statsType);
        for (StatsStoreDetail item : statsLedgerOrderList) {
            String key = this.generateKey(item, statsType);
            StatsStoreDetail statsStoreDetail = statsStoreDetailMap.get(key);
            if (StringUtils.isEmpty(statsStoreDetail)) {
                statsStoreDetail = new StatsStoreDetail();
                this.initData(statsStoreDetail, item, statsType, yesterday);
            }
            statsStoreDetail.setTotalTiktokMeituanServiceFee(item.getTotalTiktokMeituanServiceFee());
            statsStoreDetailMap.put(key, statsStoreDetail);
        }


        /**活动订单*/
        List<StatsStoreDetail> statsActivityOrderList = statsStoreDetailService.statsStatsStoreDetailByActivityOrderV2(startTime, endTime, statsType);
        for (StatsStoreDetail item : statsActivityOrderList) {

            String key = this.generateKey(item, statsType);

            StatsStoreDetail statsStoreDetail = statsStoreDetailMap.get(key);
            if (StringUtils.isEmpty(statsStoreDetail)) {
                statsStoreDetail = new StatsStoreDetail();
                this.initData(statsStoreDetail, item, statsType, yesterday);
            }

            if (StringUtils.isEmpty(statsStoreDetail.getTurnover())) {
                statsStoreDetail.setTurnover(BigDecimal.ZERO);
            }
            statsStoreDetail.setTurnover(statsStoreDetail.getTurnover().add(item.getTurnover()));

            if (StringUtils.isEmpty(statsStoreDetail.getTurnoverOnLine())) {
                statsStoreDetail.setTurnoverOnLine(BigDecimal.ZERO);
            }

            if (StringUtils.isEmpty(statsStoreDetail.getTurnoverDouYin())) {
                statsStoreDetail.setTurnoverDouYin(BigDecimal.ZERO);
            }
            if (StringUtils.isEmpty(statsStoreDetail.getTurnoverMeiTuan())) {
                statsStoreDetail.setTurnoverMeiTuan(BigDecimal.ZERO);
            }

            if (StringUtils.isEmpty(statsStoreDetail.getOrderCount())) {
                statsStoreDetail.setOrderCount(0);
            }
            statsStoreDetail.setOrderCount(statsStoreDetail.getOrderCount() + item.getOrderCount());

            if (StringUtils.isEmpty(statsStoreDetail.getOrderCountOnLine())) {
                statsStoreDetail.setOrderCountOnLine(0);
            }
            statsStoreDetail.setOrderCountOnLine(statsStoreDetail.getOrderCountOnLine() + item.getOrderCountOnLine());

            if (StringUtils.isEmpty(statsStoreDetail.getHandlingCharge())) {
                statsStoreDetail.setHandlingCharge(BigDecimal.ZERO);
            }
            statsStoreDetail.setHandlingCharge(statsStoreDetail.getHandlingCharge().add(item.getHandlingCharge()));

            if (StringUtils.isEmpty(statsStoreDetail.getSettlementMoney())) {
                statsStoreDetail.setSettlementMoney(BigDecimal.ZERO);
            }
            statsStoreDetail.setSettlementMoney(statsStoreDetail.getSettlementMoney().add(item.getSettlementMoney()));

            if (StringUtils.isEmpty(statsStoreDetail.getPlatformSettlementMoney())) {
                statsStoreDetail.setPlatformSettlementMoney(BigDecimal.ZERO);
            }
            statsStoreDetail.setPlatformSettlementMoney(statsStoreDetail.getPlatformSettlementMoney().add(item.getPlatformSettlementMoney()));

            if (StringUtils.isEmpty(statsStoreDetail.getWxMoney())) {
                statsStoreDetail.setWxMoney(BigDecimal.ZERO);
            }
            statsStoreDetail.setWxMoney(statsStoreDetail.getWxMoney().add(item.getWxMoney()));

            if (StringUtils.isEmpty(statsStoreDetail.getAliMoney())) {
                statsStoreDetail.setAliMoney(BigDecimal.ZERO);
            }

            if (StringUtils.isEmpty(statsStoreDetail.getActivityUnwrittenMoney())) {
                statsStoreDetail.setActivityUnwrittenMoney(BigDecimal.ZERO);
            }
            statsStoreDetail.setActivityUnwrittenMoney(statsStoreDetail.getActivityUnwrittenMoney().add(item.getActivityUnwrittenMoney()));

            statsStoreDetail.setAliMoney(statsStoreDetail.getAliMoney().add(item.getAliMoney()));
            statsStoreDetail.setSeckillMoney(item.getSeckillMoney());
            statsStoreDetail.setGroupBookingMoney(item.getGroupBookingMoney());
            statsStoreDetail.setConsumptionOfRedEnvelopesMoney(item.getConsumptionOfRedEnvelopesMoney());
            statsStoreDetail.setMemberOfTheStoredValueMoney(item.getMemberOfTheStoredValueMoney());

            statsStoreDetailMap.put(key, statsStoreDetail);
        }
        /**活动订单查询活动核销*/
        List<StatsStoreDetail> statsActivityOrderList1 = statsStoreDetailService.statsStatsStoreDetailByActivityOrderActivityCancelledMoney(startTime, endTime, statsType);
        for (StatsStoreDetail item : statsActivityOrderList1) {
            String key = this.generateKey(item, statsType);
            StatsStoreDetail statsStoreDetail = statsStoreDetailMap.get(key);
            if (StringUtils.isEmpty(statsStoreDetail)) {
                statsStoreDetail = new StatsStoreDetail();
                this.initData(statsStoreDetail, item, statsType, yesterday);
            }
            if (StringUtils.isEmpty(statsStoreDetail.getActivityCancelledMoney())) {
                statsStoreDetail.setActivityCancelledMoney(BigDecimal.ZERO);
            }
            statsStoreDetail.setActivityCancelledMoney(statsStoreDetail.getActivityCancelledMoney().add(item.getActivityCancelledMoney()));
            statsStoreDetailMap.put(key, statsStoreDetail);
        }

        /**统计纸钞面额-begin*/
        Integer[] deviceTypeIdArray = new Integer[]{
                DeviceTypeEnum.SUPER_MONEY_CHANGER.getCode(),
                DeviceTypeEnum.CONVERTIBLE_CURRENCY_MACHINE.getCode()
        };
        String[] channelTypeArray = new String[]{
                ChannelTypeEnum.BILL_MACHINE.getCode(),
                ChannelTypeEnum.COIN_BOX.getCode()
        };
        Integer[] orderStatusArray = new Integer[]{
                OrderStatusEnum.SUCCESS.getCode(),
                OrderStatusEnum.PART_REFUND.getCode(),
                OrderStatusEnum.FULL_FERUND.getCode(),
                OrderStatusEnum.REFUNDING.getCode(),
        };

        OrderDto orderDenomination = new OrderDto();
        orderDenomination.setStartTime(startTime);
        orderDenomination.setEndTime(endTime);
        orderDenomination.setMchType(MchTypeEnum.CASH_RECEIPTS.getCode());
        orderDenomination.setDeviceTypeIdArray(deviceTypeIdArray);
        orderDenomination.setChannelTypeArray(channelTypeArray);
        orderDenomination.setOrderStatusArray(orderStatusArray);
        List<OrderVo> orderVoList = orderService.findTurnoverOfflineGroupByDeviceNo(orderDenomination);
        if (orderVoList.size() > 0) {
            List<StatsStoreDetail> storeDetailList = new ArrayList<>();

            for (OrderVo orderVo : orderVoList) {
                orderDenomination.setDeviceNo(orderVo.getDeviceNo());
                List<OrderVo> orderList = orderService.findDenominationCountByDeviceNo(orderDenomination);

                if (orderList.size() == 0) {
                    continue;
                }

                StatsStoreDetail statsStoreDetail = new StatsStoreDetail();
                statsStoreDetail.setMchStoreId(orderList.get(0).getMerchantStoreId());
                statsStoreDetail.setDeviceNo(orderVo.getDeviceNo());
                statsStoreDetail.setOneYuanDenomination(0);
                statsStoreDetail.setFiveYuanDenomination(0);
                statsStoreDetail.setTenYuanDenomination(0);
                statsStoreDetail.setTwentyYuanDenomination(0);
                statsStoreDetail.setFiftyYuanDenomination(0);
                statsStoreDetail.setOneHundredYuanDenomination(0);
                statsStoreDetailCommonService.statsStoreDetailDenomination(orderList, statsStoreDetail);
                storeDetailList.add(statsStoreDetail);
            }

            for (StatsStoreDetail item : storeDetailList) {
                String key = this.generateKey(item, statsType);

                StatsStoreDetail statsStoreDetail = statsStoreDetailMap.get(key);
                if (StringUtils.isEmpty(statsStoreDetail)) {
                    statsStoreDetail = new StatsStoreDetail();
                    this.initData(statsStoreDetail, item, statsType, yesterday);
                }

                statsStoreDetail.setOneYuanDenomination(item.getOneYuanDenomination());
                statsStoreDetail.setFiveYuanDenomination(item.getFiveYuanDenomination());
                statsStoreDetail.setTenYuanDenomination(item.getTenYuanDenomination());
                statsStoreDetail.setTwentyYuanDenomination(item.getTwentyYuanDenomination());
                statsStoreDetail.setFiftyYuanDenomination(item.getFiftyYuanDenomination());
                statsStoreDetail.setOneHundredYuanDenomination(item.getOneHundredYuanDenomination());

                statsStoreDetailMap.put(key, statsStoreDetail);
            }
        }
        /**统计纸钞面额-end*/


        /**
         * 分片批量插入（批量数据过大）-begin
         */
        List<StatsStoreDetail> collect = statsStoreDetailMap.values().stream().collect(Collectors.toList());
        // 每批100条数据
        int size = 100;

        List<List<StatsStoreDetail>> fragmentList = new ArrayList<>();
        int maxLen = collect.size() % size == 0 ? collect.size() / size : collect.size() / size + 1;
        for (int i = 1; i <= maxLen; i++) {
            if (i == maxLen) {
                List<StatsStoreDetail> statsStoreDetails = collect.subList((i - 1) * size, collect.size());
                fragmentList.add(statsStoreDetails);
            } else {
                List<StatsStoreDetail> statsStoreDetails = collect.subList((i - 1) * size, i * size);
                fragmentList.add(statsStoreDetails);
            }
        }

        for (List<StatsStoreDetail> statsStoreDetails : fragmentList) {
            statsStoreDetailService.batchInsert(statsStoreDetails);
        }
        /**
         * 分片批量插入（批量数据过大）-end
         */


        //统计场地记录
        List<StatsStore> statsStoreList = statsStoreDao.statsStatsStoreDetailByYesterday(yesterday, statsType);

        // 循环插入数据
        for (StatsStore statsStore : statsStoreList) {
            statsStore.setDateStr(yesterday);
            MemberStoreBalanceDto memberStoreBalanceDto = new MemberStoreBalanceDto();
            memberStoreBalanceDto.setMerchantStoreId(statsStore.getMchStoreId());
            memberStoreBalanceDto.setStartTime(startTime);
            memberStoreBalanceDto.setEndTime(endTime);
            //消费新顾客数
            Integer newNum = memberStoreBalanceService.findDayMemberNewNumByStoreId(memberStoreBalanceDto);
            //现金笔数 + 抖音核销笔数 + 美团核销笔数
            StatsStoreDetail statsStoreDetail1 = statsStoreDetailService.finMemberIdCount(memberStoreBalanceDto);
            //现金笔数 + 抖音核销笔数 + 美团核销笔数 + 消费新顾客数
            statsStore.setMemberConsumeNewNum(
                    newNum +
                            statsStoreDetail1.getCashCount() +
                            statsStoreDetail1.getDouYinCount() +
                            statsStoreDetail1.getMeiTuanCount());
            //统计当天场地 老顾客
            Integer oldNum = memberStoreBalanceService.findDayMemberOldNumByStoreId(memberStoreBalanceDto);
            statsStore.setMemberConsumeOldNum(oldNum);

            //消费顾客 消费新顾客数 + 消费老顾客数。
            statsStore.setMemberConsumeNum(statsStore.getMemberConsumeNewNum() + statsStore.getMemberConsumeOldNum());

            statsStore.setType(TYPE_DAY);

            //活动最高和最低
            StatsStoreDetail activityStatsStoreDetail = statsStoreDetailService.findActivityOrderMaxAndMin(startTime, endTime, statsStore.getMchStoreId());
            //最高客单价
            Integer max = statsStoreDetail1.getMaxTotalAmount().compareTo(activityStatsStoreDetail.getMaxTotalAmount());
            statsStore.setMaximumUnitPrice(max < 0 ? activityStatsStoreDetail.getMaxTotalAmount() : statsStoreDetail1.getMaxTotalAmount());
            //最低客单价
            Integer min = statsStoreDetail1.getMinTotalAmount().compareTo(activityStatsStoreDetail.getMinTotalAmount());
            statsStore.setMiniimumUnitPrice(min < 0 ? activityStatsStoreDetail.getMinTotalAmount() : statsStoreDetail1.getMinTotalAmount());
            Integer countPhoneNumber = memberDao.findCountByMerchantStoreId(startTime, endTime, statsStore.getMchStoreId());
            statsStore.setLeaveMemberPhoneNumber(countPhoneNumber);

            ConsumeRecordDto consumeRecordDto = new ConsumeRecordDto();
            consumeRecordDto.setMerchantStoreId(statsStore.getMchStoreId());
            consumeRecordDto.setStartTime(startTime);
            consumeRecordDto.setEndTime(endTime);
            consumeRecordDto.setConsumeRecordTypeId(ConsumeRecordTypeEnum.CONSUME.getCode());
            statsStoreDao.insert(statsStore);

            StatsStoreDetail statsStoreDetail = new StatsStoreDetail();
            statsStoreDetail.setStatsStoreId(statsStore.getId());
            statsStoreDetail.setDateStr(statsStore.getDateStr());
            statsStoreDetail.setMchStoreId(statsStore.getMchStoreId());
            statsStoreDetailService.updateByDateAndMchStoreId(statsStoreDetail);
        }


        /**扣除合利宝节假日万2手续费，在支付回调扣除吧*/

    }

    @Override
    public ServerResponse exportStatsStoreList(StatsStoreDto statsStoreDto) {
        if (statsStoreDto.getType().equals(1)) {
            statsStoreDto.setStartDateStr(DateTimeUtils.formatByPattern(statsStoreDto.getCreateTime(), "yyyy-MM-dd"));
            statsStoreDto.setEndDateStr(DateTimeUtils.formatByPattern(statsStoreDto.getUpdateTime(), "yyyy-MM-dd"));
        } else {
            statsStoreDto.setStartDateStr(DateTimeUtils.formatByPattern(statsStoreDto.getCreateTime(), "yyyy-MM"));
            statsStoreDto.setEndDateStr(DateTimeUtils.formatByPattern(statsStoreDto.getUpdateTime(), "yyyy-MM"));
        }
        List<StatsStoreVo> statsStoreVoList = statsStoreDao.findList(statsStoreDto);
        if(StringUtils.isEmpty(statsStoreVoList) || statsStoreVoList.size() == 0){
            return ServerResponse.createByErrorMessage("没有数据，可以导出");
        }
        statsStoreVoList.forEach(data -> {
            data.setActivityTurnover(data.getSeckillMoney().add(data.getGroupBookingMoney()).add(data.getConsumptionOfRedEnvelopesMoney()).add(data.getMemberOfTheStoredValueMoney()));
        });

        String[] headers = new String[]{"日期","合作伙伴", "运营商", "场地","营业额（元）", "扫码支付（元）","现金收入（元）","活动收入（元）","抖音核销（元）","美团核销（元）","预计结算金额（单位：元）未扣除节假日结算的万分之二结算手续费，实际到账请前往【结算查询】","订单笔数","线上订单笔数","线下订单笔数","消费会员（个）","新增会员（个）"};
        // 定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 设置时区为东八区
        // 格式化日期
        String formattedCreateTime = sdf.format(statsStoreDto.getCreateTime());
        String formattedUpdateTime = sdf.format(statsStoreDto.getUpdateTime());
        String sheetName = "场地统计" + formattedCreateTime + "至" + formattedUpdateTime;
        // 创建了一个excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet(sheetName);
        sheet.setDefaultColumnWidth(10);
        sheet.setColumnWidth(0, 30 * 256);
        sheet.setColumnWidth(1, 30 * 256);
        sheet.setColumnWidth(2, 25 * 256);
        sheet.setColumnWidth(3, 25 * 256);
        sheet.setColumnWidth(8, 25 * 256);
//        sheet.createFreezePane(0, 4, 0, 4);
        //标题样式
        HSSFCellStyle titleStyle = wb.createCellStyle(); // 样式对象
        //设置标题字体格式
        Font font = wb.createFont();
        //设置字体样式
        //font.setFontHeightInPoints((short) 20);   //--->设置字体大小
        font.setFontName("Courier New");   //---》设置字体，是什么类型例如：宋体
        font.setItalic(true);     //--->设置是否是加粗
        titleStyle.setFont(font);     //--->将字体格式加入到style1中
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平
        titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //垂直

        //内容样式
        HSSFCellStyle contextStyle = wb.createCellStyle(); // 样式对象
        //设置标题字体格式
        Font contextfont = wb.createFont();
        contextfont.setFontHeightInPoints((short) 13);   //--->设置字体大小
        //设置字体样式
        contextStyle.setFont(contextfont);     //--->将字体格式加入到style1中
        contextStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平
        contextStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //垂直
        contextStyle.setWrapText(true);//设置自动换行

        //表格第一行
        HSSFRow row1 = sheet.createRow(0);   //--->创建一行
        row1.setHeightInPoints(20);
        HSSFCell cell1 = row1.createCell(0);   //--->创建一个单元格
        // cell1.setCellStyle(titleStyle);
        cell1.setCellValue("场地统计");
        //表格第二行
        HSSFRow r2 = sheet.createRow(1);
        r2.setHeightInPoints(20);
        HSSFCell c2 = r2.createCell(0);
        c2.setCellValue("起始时间：[" + sdf.format(statsStoreDto.getCreateTime()) + "]  " + "  终止时间：[" + sdf.format(statsStoreDto.getUpdateTime()) + "]");

        //标题
        HSSFRow row2 = sheet.createRow(3);           //--->创建一行
        contextStyle.setFillForegroundColor(HSSFColor.LEMON_CHIFFON.index);// 设置背景色
        contextStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        contextStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
        contextStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
        contextStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
        contextStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
        contextfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示
        contextStyle.setFont(contextfont);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell2 = row2.createCell(i);
            cell2.setCellValue(headers[i]);
            cell2.setCellStyle(contextStyle);
        }
        int index = 0;//记录额外创建的sheet数量
        int j = 0;
        // 循环每行
        for (int i = 4; i < statsStoreVoList.size() + 4; i++) {
            if ((i) % 65500 == 0) {
                sheet = wb.createSheet("salesList" + index);
                index++;
            }
            // 创建行
            HSSFRow row = sheet.createRow((i) - (index * 65500));


            //日期
            HSSFCell contextCell0 = row.createCell(0);
            contextCell0.setCellValue(statsStoreVoList.get(j).getDateStr());

            //合作伙伴
            HSSFCell contextCell1 = row.createCell(1);
            if (!StringUtils.isEmpty(statsStoreVoList.get(j).getAgencyName())) {
                contextCell1.setCellValue(statsStoreVoList.get(j).getAgencyName());
            } else {
                contextCell1.setCellValue("无");
            }

            //运营商
            String userName = "";
            HSSFCell contextCell2 = row.createCell(2);
            if (!StringUtils.isEmpty(statsStoreVoList.get(j).getName())) {
                userName =statsStoreVoList.get(j).getName() + ":";
                contextCell2.setCellValue(statsStoreVoList.get(j).getName());
            } else {
                contextCell2.setCellValue("");
            }
            if(!StringUtils.isEmpty(statsStoreVoList.get(j).getUsername())){
                contextCell2.setCellValue(userName + statsStoreVoList.get(j).getUsername());
            }

            //场地
            HSSFCell contextCell3 = row.createCell(3);
            if (!StringUtils.isEmpty(statsStoreVoList.get(j).getStoreName())) {
                contextCell3.setCellValue(statsStoreVoList.get(j).getStoreName());
            } else {
                contextCell3.setCellValue("无");
            }

            //营业额（元）
            HSSFCell contextCell4 = row.createCell(4);
            if(!StringUtils.isEmpty(statsStoreVoList.get(j).getTurnover())){
                contextCell4.setCellValue(statsStoreVoList.get(j).getTurnover().toString());
            }else{
                contextCell4.setCellValue("");
            }

            //扫码支付（元）
            HSSFCell contextCell5 = row.createCell(5);
            if (!StringUtils.isEmpty(statsStoreVoList.get(j).getTurnoverOnLine())) {
                contextCell5.setCellValue(statsStoreVoList.get(j).getTurnoverOnLine().toString());
            } else {
                contextCell5.setCellValue("");
            }

            //现金收入（元）
            HSSFCell contextCell6 = row.createCell(6);
            if (!StringUtils.isEmpty(statsStoreVoList.get(j).getTurnoverOffline())) {
                contextCell6.setCellValue(statsStoreVoList.get(j).getTurnoverOffline().toString());
            } else {
                contextCell6.setCellValue("");
            }

            //活动收入（元）
            HSSFCell contextCell7 = row.createCell(7);
            if (!StringUtils.isEmpty(statsStoreVoList.get(j).getActivityTurnover())) {
                contextCell7.setCellValue(statsStoreVoList.get(j).getActivityTurnover().toString());
            } else {
                contextCell7.setCellValue("");
            }

            //抖音核销（元）
            HSSFCell contextCell8 = row.createCell(8);
            if (!StringUtils.isEmpty(statsStoreVoList.get(j).getTurnoverDouYin())) {
                contextCell8.setCellValue(statsStoreVoList.get(j).getTurnoverDouYin().toString());
            } else {
                contextCell8.setCellValue("");
            }

            //美团核销（元）
            HSSFCell contextCell9 = row.createCell(9);
            if (!StringUtils.isEmpty(statsStoreVoList.get(j).getTurnoverMeiTuan())) {
                contextCell9.setCellValue(statsStoreVoList.get(j).getTurnoverMeiTuan().toString());
            } else {
                contextCell9.setCellValue("");
            }

            //结算金额（元）
            HSSFCell contextCell10 = row.createCell(10);
            if (!StringUtils.isEmpty(statsStoreVoList.get(j).getSettlementMoney())) {
                contextCell10.setCellValue(statsStoreVoList.get(j).getSettlementMoney().toString());
            } else {
                contextCell10.setCellValue("");
            }

            //订单笔数
            HSSFCell contextCell11 = row.createCell(11);
            if(!StringUtils.isEmpty(statsStoreVoList.get(j).getOrderCount())){
                contextCell11.setCellValue(statsStoreVoList.get(j).getOrderCount());
            }else{
                contextCell11.setCellValue("");
            }

            //线上订单笔数
            HSSFCell context1Cell12 = row.createCell(12);
            if(!StringUtils.isEmpty(statsStoreVoList.get(j).getOrderCountOnLine())){
                context1Cell12.setCellValue(statsStoreVoList.get(j).getOrderCountOnLine());
            }else{
                context1Cell12.setCellValue("");
            }

            //线上订单笔数
            HSSFCell conte1t1Cell13= row.createCell(13);
            if(!StringUtils.isEmpty(statsStoreVoList.get(j).getOrderCountOffline())){
                conte1t1Cell13.setCellValue(statsStoreVoList.get(j).getOrderCountOffline());
            }else{
                conte1t1Cell13.setCellValue("");
            }

            //消费会员（个）
            HSSFCell conte11t1Cell14 = row.createCell(14);
            if(!StringUtils.isEmpty(statsStoreVoList.get(j).getMemberConsumeNum())){
                conte11t1Cell14.setCellValue(statsStoreVoList.get(j).getMemberConsumeNum());
            }else{
                conte11t1Cell14.setCellValue("");
            }

            //消费会员（个）
            HSSFCell conte11t11Cell15 = row.createCell(15);
            if(!StringUtils.isEmpty(statsStoreVoList.get(j).getMemberNewNum())){
                conte11t11Cell15.setCellValue(statsStoreVoList.get(j).getMemberNewNum());
            }else{
                conte11t11Cell15.setCellValue("");
            }

            j++;
            if (j >= statsStoreVoList.size()) {
                j = 0;
            }
        }
        // 保存文件
        FileOutputStream fileOut = null;
        String fileName = fileProperties.getSaveImgPath() + "/" + sheetName + ".xls";

        try {
            File f = new File(fileName);
            if (!f.exists()) {
                f.createNewFile();
            }
            // 文件保存的地址和名称
            log.info("------------------------------iot后台库存记录导出:" + fileName);
            fileOut = new FileOutputStream(fileName);
            wb.write(fileOut);

        } catch (IOException e) {
            // 处理文件操作可能发生的IO异常
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("文件保存失败:" + e + fileProperties.getSaveImgPath());
        } catch (Exception e) {
            // 其他异常
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("文件保存过程中发生了错误:" + e);

        } finally {
            // 关闭流
            if (fileOut != null) {
                try {
                    fileOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        Map<String, String> map = new HashMap<>();
        map.put("fileName", sheetName + ".xls");
        map.put("downloadUrl",configProperties.getAdminBackEndUrl() + "/api/fileExport/download/" +sheetName + ".xls");
        return ServerResponse.createBySuccess(map);
    }

    /**
     * 生成key
     *
     * @param item
     * @param statsType
     * @return
     */
    private String generateKey(StatsStoreDetail item, Integer statsType) {
        if (StatsTypeEnum.statsUser.getCode().compareTo(statsType) == 0) {
            return new StringBuffer(String.valueOf(item.getMemberId())).append("_").append(item.getMchStoreId()).toString();
        } else if (StatsTypeEnum.onDeviceStatsUser.getCode().compareTo(statsType) == 0) {
            return new StringBuffer(String.valueOf(item.getMemberId())).append("_").append(item.getMchStoreId()).append("_").append(item.getDeviceNo()).toString();
        } else {
            throw new RuntimeException("StatsType-key不存在");
        }
    }

    /**
     * 检查从map get出来的结果是否null
     *
     * @param statsStoreDetail
     * @param item
     * @param statsType
     * @param yesterday
     */
    private void initData(StatsStoreDetail statsStoreDetail, StatsStoreDetail item, Integer statsType, String yesterday) {
        if (StatsTypeEnum.statsUser.getCode().compareTo(statsType) == 0) {
            statsStoreDetail.setMchStoreId(item.getMchStoreId());
        } else if (StatsTypeEnum.onDeviceStatsUser.getCode().compareTo(statsType) == 0) {
            statsStoreDetail.setDeviceNo(item.getDeviceNo());
            statsStoreDetail.setMchStoreId(item.getMchStoreId());
        }

        statsStoreDetail.setType(TYPE_DAY);
        statsStoreDetail.setStatsType(statsType);
        statsStoreDetail.setDateStr(yesterday);
        statsStoreDetail.setMemberId(item.getMemberId());
    }

    @Override
    public List<StatsStoreVo> findMerchantTurnoverTop(StatsStoreDto statsStoreDto) {
        if (statsStoreDto.getType().equals(1)) {
            statsStoreDto.setStartDateStr(DateTimeUtils.getMonthFirstDay());
            statsStoreDto.setEndDateStr(DateTimeUtils.getMonthLastDay());
        } else {
            statsStoreDto.setStartDateStr(DateTimeUtils.getYearFirstDay());
            statsStoreDto.setEndDateStr(DateTimeUtils.getYearLastDay());
        }
        List<StatsStoreVo> list = statsStoreDao.findMerchantTurnoverTop(statsStoreDto);
        if(statsStoreDto.getUserInfo().getId().compareTo(172)==0){
            list.forEach(item->{
                item.setOrderCount(item.getOrderCount() * 50);
            });
        }
        return list;
    }

    @Override
    public List<StatsStoreVo> findMerchantOrderCountTop(StatsStoreDto statsStoreDto) {
        if (statsStoreDto.getType().equals(1)) {
            statsStoreDto.setStartDateStr(DateTimeUtils.getMonthFirstDay());
            statsStoreDto.setEndDateStr(DateTimeUtils.getMonthLastDay());
        } else {
            statsStoreDto.setStartDateStr(DateTimeUtils.getYearFirstDay());
            statsStoreDto.setEndDateStr(DateTimeUtils.getYearLastDay());
        }
        List<StatsStoreVo> list = statsStoreDao.findMerchantOrderCountTop(statsStoreDto);
        if(statsStoreDto.getUserInfo().getId().compareTo(172)==0){
            list.forEach(item->{
                item.setOrderCount(item.getOrderCount() * 50);
            });
        }
        return list;
    }
}
